package cn.glinks.liuhe.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import cn.glinks.liuhe.R;
import cn.glinks.liuhe.api.ApiConstants;
import cn.glinks.liuhe.api.ApiRequest;
import cn.glinks.liuhe.api.jsonbean.Companys;
import cn.glinks.liuhe.api.jsonbean.RegisterInfo;
import cn.glinks.liuhe.api.jsonbean.UserInfo;
import cn.glinks.liuhe.app.AppApplication;
import cn.glinks.liuhe.app.AppConstant;
import cn.glinks.liuhe.base.BaseActivity;
import cn.glinks.liuhe.baserx.RxSubscriber;
import cn.glinks.liuhe.model.Interest;
import cn.glinks.liuhe.utils.ActTransAnimUtils;
import cn.glinks.liuhe.utils.DisplayUtils;
import cn.glinks.liuhe.utils.FormatUtils;
import cn.glinks.liuhe.utils.GsonUtils;
import cn.glinks.liuhe.utils.SPUtils;
import cn.glinks.liuhe.utils.SmscodeCountDownTimerUtils;
import cn.glinks.liuhe.utils.SoftInputUtils;
import cn.glinks.liuhe.utils.ToastUtils;
import cn.glinks.liuhe.widget.pickerview.FlatOptionsPickerView;
import cn.glinks.liuhe.widget.pickerview.FlatTimePickerView;
import cn.glinks.liuhe.widget.pickerview.PickerViewDataLoader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Des:注册页面
 *
 * @author MarsBlade of Cyh
 * @created 2017-03-21 14:43
 */
public class RegisterActivity extends BaseActivity {

  @BindView(R.id.tv_title)
  TextView mTitleText;

  @BindView(R.id.iv_agree)
  ImageView mAgreeImage;

  @BindView(R.id.sv_input)
  ScrollView mScrollView;

  @BindView(R.id.btn_next)
  Button mNextButton;

  /*---------------基本情况->START---------------*/
  @BindView(R.id.et_name) //姓名
      EditText mNameEdit;

  @BindView(R.id.et_id)   //身份证号
      EditText mIdEdit;

  @BindView(R.id.et_company) //公司
      EditText mCompanyEdit;

  @BindView(R.id.et_park) //单位
      EditText mParkEdit;

  @BindView(R.id.et_emid) //工号
      EditText mEmidEdit;

  private String mNameStr;
  private String mIdStr;
  private String mCompanyStr;
  private String mParkStr;
  private String mEmidStr;
    /*---------------基本情况->END-----------------*/

  /*---------------个人资料->START---------------*/
  @BindView(R.id.et_sex)              //性别
      EditText mSexEdit;

  @BindView(R.id.et_birthday)         //出生年月
      EditText mBirthdayEdit;

  @BindView(R.id.et_race)             //民族
      EditText mRaceEdit;

  @BindView(R.id.et_marital)          //婚姻
      EditText mMaritalEdit;

  @BindView(R.id.et_education)        //学历
      EditText mEducationEdit;

  @BindView(R.id.et_graduate_time)    //毕业时间
      EditText mGraduateTimeEdit;

  @BindView(R.id.et_graduate_school)  //毕业院校
      EditText mGraduateSchoolEdit;

  @BindView(R.id.et_major)            //所学专业
      EditText mMajorEdit;

  @BindView(R.id.et_worktime)        //工作年资
      EditText mWorktimeEdit;

  @BindView(R.id.et_life_experience)  //成长经历
      EditText mLifeExperienceEdit;

  private String mSexStr;
  private String mBirthdayStr;
  private String mRaceStr;
  private String mMaritalStr;
  private String mEducationStr;
  private String mGraduateTimeStr;
  private String mGraduateSchoolStr;
  private String mMajorStr;
  private String mWorktimeStr;
  private String mLifeExperienceStr;
    /*---------------个人资料->END-----------------*/

  /*---------------爱好和性格->START---------------*/
  @BindView(R.id.et_hobby)            // 爱好
      EditText mHobbyEdit;

  @BindView(R.id.et_sport)            // 运动
      EditText mSportEdit;

  @BindView(R.id.et_travel)           // 旅游
      EditText mTravelEdit;

  @BindView(R.id.et_intercourse)      // 交往
      EditText mIntercourseEdit;

  @BindView(R.id.et_living)           // 居住
      EditText mLivingEdit;

  @BindView(R.id.et_character)        // 性格
      EditText mCharacterEdit;

  private String mHobbyStr;
  private String mSportStr;
  private String mTravelStr;
  private String mIntercourseStr;
  private String mLivingStr;
  private String mCharacterStr;
    /*---------------爱好和性格->END-----------------*/

  /*---------------注册资料->START---------------*/
  @BindView(R.id.et_phone)    //手机号
      EditText mPhoneEdit;

  @BindView(R.id.tv_smscode)  //验证码按钮
      TextView mSmscodeText;

  @BindView(R.id.et_smscode)  //验证码文本
      EditText mSmscodeEdit;

  @BindView(R.id.et_passwd)   //密码
      EditText mPasswdEdit;

  private String mPhoneStr;
  private String mSmscodeStr;
  private String mPasswdStr;
    /*---------------注册资料->END-----------------*/

  // 选择器数据缓存
  private ArrayList<String> mCompanyList = new ArrayList<>();
  private ArrayList<String> mParkList = new ArrayList<>();
  private ArrayList<String> mSexList;
  private ArrayList<String> mRaceList;
  private ArrayList<String> mMaritalList;
  private ArrayList<String> mEducationList;
  private ArrayList<String> mWorktimeList;

  // 选择器PickerView
  private FlatOptionsPickerView mCompanyFOPV;
  private FlatOptionsPickerView mParkFOPV;
  private FlatOptionsPickerView mSexFOPV;
  private FlatTimePickerView mBirthdayFTPV;
  private FlatOptionsPickerView mRaceFOPV;
  private FlatOptionsPickerView mMaritalFOPV;
  private FlatOptionsPickerView mEducationFOPV;
  private FlatOptionsPickerView mWorktimeFOPV;
  private FlatTimePickerView mGraduateTimeFTPV;

  // 其他变量
  private boolean isAgree = false;//是否同意服务协议标志位
  private Companys mCompanyJson = null;// 公司列表缓存
  private String mCompanyCode = "";// 当前公司代码


  @Override
  public int getLayoutId() {
    return R.layout.activity_register;
  }

  @Override
  public void initView(Bundle savedInstanceState) {
    // 设置为透明状态栏
    SetTranslanteBar();
    // 初始化标题
    mTitleText.setText("注册");
    // 加载选择器数据
    initOptionData();
    // 初始化子控件交互动作
    initViewActions();
    // 初始化爱好和性格显示数据
    showInterestData();
  }

  @Override
  protected void onResume() {
    super.onResume();

    boolean isChanged = SPUtils.getSharedBooleanData(this, AppConstant.IS_INTEREST_CHANGED);
    if (isChanged) {
      // 更新爱好和性格显示数据
      showInterestData();
    }

    mTitleText.setFocusableInTouchMode(true);
    mTitleText.setFocusable(true);
    mTitleText.requestFocus();
  }

    /*--------------------------------------------------------------------------------
     *                          基本封装接口
     ---------------------------------------------------------------------------------*/

  /**
   * Des:加载选择器全部数据
   */
  private void initOptionData() {
    // 加载选择器(其他)数据到UI
    mSexList = PickerViewDataLoader.loadSex();
    mRaceList = PickerViewDataLoader.loadRace();
    mMaritalList = PickerViewDataLoader.loadMarital();
    mEducationList = PickerViewDataLoader.loadEducation();
    mWorktimeList = PickerViewDataLoader.loadWorktime();
    // 加载选择器(公司)数据到UI
    String data = SPUtils.getSharedStringData(RegisterActivity.this, AppConstant.SP_KEY_COMPANY_JSON);
    mCompanyJson = (Companys) GsonUtils.fromJson(data, Companys.class);
    mCompanyList.clear();
    for (int i = 0; i < mCompanyJson.getCompanies().size(); i++) {
      mCompanyList.add(mCompanyJson.getCompanies().get(i).getCompany());
    }
  }

  /**
   * Des:动态加载Park选择器数据
   */
  private void reloadParkOptionData(int pos) {
    Companys.CompaniesBean companyBean = mCompanyJson.getCompanies().get(pos);

    // 判断是否属于切换公司的动作, 属于则重新加载单位数据
    if (!companyBean.getCompany().equals(mCompanyCode)) {
      mCompanyCode = companyBean.getCompany();
      mParkEdit.setText("");
      // 重新加载单位数据
      mParkList.clear();
      for (int i = 0; i < companyBean.getSubcompany().size(); i++) {
        mParkList.add(companyBean.getSubcompany().get(i));
      }
      mParkFOPV = buildParkPickerView(mParkList);
    }
  }

  /**
   * Des:根据指定单位代码加载Park选择器数据
   */
  private boolean reloadParkOptionData(String code) {
    for (int i = 0; i < mCompanyJson.getCompanies().size(); i++) {
      Companys.CompaniesBean companyBean = mCompanyJson.getCompanies().get(i);
      // 判断是否存在此单位代码, 存在则重新加载单位数据
      if (companyBean.getCompany().equals(code)) {
        mCompanyCode = companyBean.getCompany();
        mParkEdit.setText("");
        // 重新加载单位数据
        mParkList.clear();
        for (int j = 0; j < companyBean.getSubcompany().size(); j++) {
          mParkList.add(companyBean.getSubcompany().get(j));
        }
        mParkFOPV = buildParkPickerView(mParkList);
        return true;
      }
    }

    // 清空单位数据
    mCompanyCode = "";
    mParkEdit.setText("");
    mParkList.clear();
    mParkFOPV = buildParkPickerView(mParkList);
    return false;
  }

  /**
   * Des:设置控件交互动作
   */
  private void setEditTextAction(final EditText editText) {
    editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
      @Override
      public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
          scrollToTop(editText);
        }
      }
    });
    editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
      @Override
      public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_NEXT) {
          SoftInputUtils.hideSoftKeyboard(RegisterActivity.this);
          return true;
        }
        return false;
      }
    });
  }

  /**
   * Des:初始化子控件交互动作
   */

  private void initViewActions() {
//    mCompanyEdit.setInputType(InputType.TYPE_NULL);
//    mCompanyEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//      @Override
//      public void onFocusChange(View v, boolean hasFocus) {
//        SoftInputUtils.hideSoftKeyboard(RegisterActivity.this);
//        if (hasFocus) {
//          scrollToTop(mCompanyEdit);
//          if (null == mCompanyFOPV) {
//            mCompanyFOPV = buildCompanyPickerView();
//          }
//          mCompanyFOPV.show();
//        }
//      }
//    });
    mCompanyEdit.addTextChangedListener(new TextWatcher() {
      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {

      }

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {

      }

      @Override
      public void afterTextChanged(Editable s) {
        // 输入单位代码时重载分支机构数据
        reloadParkOptionData(s.toString().trim());
      }
    });
    mParkEdit.setInputType(InputType.TYPE_NULL);
    mParkEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
      @Override
      public void onFocusChange(View v, boolean hasFocus) {
        // 判断是否已选择公司
        SoftInputUtils.hideSoftKeyboard(RegisterActivity.this);
        if (hasFocus) {
          if (mCompanyCode.isEmpty()) {
            ToastUtils.showShort("请先输入有效的单位代码");
            return;
          }
          scrollToTop(mParkEdit);
          if (null == mParkFOPV) {
            mParkFOPV = buildParkPickerView(mParkList);
          }
          mParkFOPV.show();
        }
      }
    });
    mSexEdit.setInputType(InputType.TYPE_NULL);
    mSexEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
      @Override
      public void onFocusChange(View v, boolean hasFocus) {
        SoftInputUtils.hideSoftKeyboard(RegisterActivity.this);
        if (hasFocus) {
          scrollToTop(mSexEdit);
          if (null == mSexFOPV) {
            mSexFOPV = buildSexPickerView();
          }
          mSexFOPV.show();
        }
      }
    });
    mBirthdayEdit.setInputType(InputType.TYPE_NULL);
    mBirthdayEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
      @Override
      public void onFocusChange(View v, boolean hasFocus) {
        SoftInputUtils.hideSoftKeyboard(RegisterActivity.this);
        if (hasFocus) {
          scrollToTop(mBirthdayEdit);
          if (null == mBirthdayFTPV) {
            mBirthdayFTPV = buildBirthdayPickerView();
          }
          mBirthdayFTPV.show();
        }
      }
    });
    mRaceEdit.setInputType(InputType.TYPE_NULL);
    mRaceEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
      @Override
      public void onFocusChange(View v, boolean hasFocus) {
        SoftInputUtils.hideSoftKeyboard(RegisterActivity.this);
        if (hasFocus) {
          scrollToTop(mRaceEdit);
          if (null == mRaceFOPV) {
            mRaceFOPV = buildRacePickerView();
          }
          mRaceFOPV.show();
        }
      }
    });
    mMaritalEdit.setInputType(InputType.TYPE_NULL);
    mMaritalEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
      @Override
      public void onFocusChange(View v, boolean hasFocus) {
        SoftInputUtils.hideSoftKeyboard(RegisterActivity.this);
        if (hasFocus) {
          scrollToTop(mMaritalEdit);
          if (null == mMaritalFOPV) {
            mMaritalFOPV = buildMaritalPickerView();
          }
          mMaritalFOPV.show();
        }
      }
    });
    mEducationEdit.setInputType(InputType.TYPE_NULL);
    mEducationEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
      @Override
      public void onFocusChange(View v, boolean hasFocus) {
        SoftInputUtils.hideSoftKeyboard(RegisterActivity.this);
        if (hasFocus) {
          scrollToTop(mEducationEdit);
          if (null == mEducationFOPV) {
            mEducationFOPV = buildEducationPickerView();
          }
          mEducationFOPV.show();
        }
      }
    });
    mWorktimeEdit.setInputType(InputType.TYPE_NULL);
    mWorktimeEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
      @Override
      public void onFocusChange(View v, boolean hasFocus) {
        SoftInputUtils.hideSoftKeyboard(RegisterActivity.this);
        if (hasFocus) {
          scrollToTop(mWorktimeEdit);
          if (null == mWorktimeFOPV) {
            mWorktimeFOPV = buildWorktimePickerView();
          }
          mWorktimeFOPV.show();
        }
      }
    });
    mGraduateTimeEdit.setInputType(InputType.TYPE_NULL);
    mGraduateTimeEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
      @Override
      public void onFocusChange(View v, boolean hasFocus) {
        SoftInputUtils.hideSoftKeyboard(RegisterActivity.this);
        if (hasFocus) {
          scrollToTop(mGraduateTimeEdit);
          if (null == mGraduateTimeFTPV) {
            mGraduateTimeFTPV = buildGraduateTimePickerView();
          }
          mGraduateTimeFTPV.show();
        }
      }
    });
    setEditTextAction(mNameEdit);
    setEditTextAction(mIdEdit);
    setEditTextAction(mEmidEdit);
    setEditTextAction(mGraduateSchoolEdit);
    setEditTextAction(mMajorEdit);
    setEditTextAction(mLifeExperienceEdit);
  }

  /**
   * Des:重载全部填写数据
   */
  private RegisterInfo reloadAllEditData() {
    RegisterInfo info = new RegisterInfo();
    RegisterInfo.BasicBean infoBasic = new RegisterInfo.BasicBean();
    RegisterInfo.BasicBean.UnitBean unitBean = new RegisterInfo.BasicBean.UnitBean();
    RegisterInfo.PersonalInfoBean infoPersonalInfo = new RegisterInfo.PersonalInfoBean();
    RegisterInfo.PersonalInterestBean infoPersonalInterest = new RegisterInfo.PersonalInterestBean();
    RegisterInfo.NeedBean infoNeed = new RegisterInfo.NeedBean();

    // 获取基本情况数据
    mNameStr = mNameEdit.getText().toString().trim();
    mIdStr = mIdEdit.getText().toString().trim();

    mEmidStr = mEmidEdit.getText().toString().trim();
    infoBasic.setName(mNameStr);
    infoBasic.setIdNo(mIdStr);
    infoBasic.setEmid(mEmidStr);
    info.setBasic(infoBasic);

    // 单位详情数据
    mCompanyStr = mCompanyEdit.getText().toString().trim();
    mParkStr = mParkEdit.getText().toString().trim();
    unitBean.setUnitCode(mCompanyStr);
    unitBean.setBranch(mParkStr);
    info.getBasic().setUnit(unitBean);

    // 获取个人资料数据
    mSexStr = mSexEdit.getText().toString().trim();
    mBirthdayStr = mBirthdayEdit.getText().toString().trim();
    mRaceStr = mRaceEdit.getText().toString().trim();
    mMaritalStr = mMaritalEdit.getText().toString().trim();
    mEducationStr = mEducationEdit.getText().toString().trim();
    mGraduateTimeStr = mGraduateTimeEdit.getText().toString().trim();
    mGraduateSchoolStr = mGraduateSchoolEdit.getText().toString().trim();
    mMajorStr = mMajorEdit.getText().toString().trim();
    mWorktimeStr = mWorktimeEdit.getText().toString().trim();
    mLifeExperienceStr = mLifeExperienceEdit.getText().toString().trim();
    if (mSexStr.equals("女")) {
      infoPersonalInfo.setSex(0);
    } else {
      infoPersonalInfo.setSex(1);
    }
    infoPersonalInfo.setBirthDate(mBirthdayStr.replace("年", "-").replace("月", ""));
    infoPersonalInfo.setNationality(mRaceStr);
    infoPersonalInfo.setMarried(mMaritalStr);
    infoPersonalInfo.setEducation(mEducationStr);
    infoPersonalInfo.setGraduateTime(mGraduateTimeStr.replace("年", "-").replace("月", ""));
    infoPersonalInfo.setCollege(mGraduateSchoolStr);
    infoPersonalInfo.setSpecialty(mMajorStr);
    if (mWorktimeStr.equals("0至6个月")) {
      infoPersonalInfo.setWorkTime("1");
    } else if(mWorktimeStr.equals("6个月至2年")) {
      infoPersonalInfo.setWorkTime("2");
    } else {
      infoPersonalInfo.setWorkTime("3");
    }
    infoPersonalInfo.setGrowthExp(mLifeExperienceStr);
    info.setPersonalInfo(infoPersonalInfo);

    // 获取爱好和性格数据
    mHobbyStr = mHobbyEdit.getText().toString().trim().replace("、", "|");
    mSportStr = mSportEdit.getText().toString().trim().replace("、", "|");
    mTravelStr = mTravelEdit.getText().toString().trim().replace("、", "|");
    mIntercourseStr = mIntercourseEdit.getText().toString().trim().replace("、", "|");
    mLivingStr = mLivingEdit.getText().toString().trim().replace("、", "|");
    mCharacterStr = mCharacterEdit.getText().toString().trim().replace("、", "|");
    infoPersonalInterest.setHobby(mHobbyStr);
    infoPersonalInterest.setSport(mSportStr);
    infoPersonalInterest.setTravel(mTravelStr);
    infoPersonalInterest.setIntercourse(mIntercourseStr);
    infoPersonalInterest.setLiving(mLivingStr);
    infoPersonalInterest.setCharacter(mCharacterStr);
    info.setPersonalInterest(infoPersonalInterest);

    // 获取注册资料数据
    mPhoneStr = mPhoneEdit.getText().toString().trim();
    mSmscodeStr = mSmscodeEdit.getText().toString().trim();
    mPasswdStr = mPasswdEdit.getText().toString().trim();
    infoNeed.setPhoneNo(mPhoneStr);
    infoNeed.setSmscode(mSmscodeStr);
    infoNeed.setPassword(mPasswdStr);
    info.setNeed(infoNeed);

    return info;
  }

  /**
   * Des:检查全部填写数据的有效性
   */
  private boolean checkAllEditData(RegisterInfo info) {
    // 检查基本情况数据
    if (info.getBasic().getName().isEmpty()) {
      ToastUtils.showShort("请填写姓名");
      return false;
    }
//        if (info.getBasic().getIdNo().isEmpty() || !FormatUtils.isIdCardNo(info.getBasic().getIdNo())) {
//            ToastUtils.showShort("请填写正确的身份证号");
//            return false;
//        }
    if (info.getBasic().getUnit().getUnitCode().isEmpty()) {
      ToastUtils.showShort("请选择单位");
      return false;
    }
    if (info.getBasic().getEmid().isEmpty()) {
      ToastUtils.showShort("请填写正确的工号");
      return false;
    }

    // 检查个人资料数据
    if (info.getPersonalInfo().getSex() < 0) {
      ToastUtils.showShort("请选择性别");
      return false;
    }
    if (info.getPersonalInfo().getBirthDate().isEmpty()) {
      ToastUtils.showShort("请选择出生年月");
      return false;
    }
    if (info.getPersonalInfo().getNationality().isEmpty()) {
      ToastUtils.showShort("请选择民族");
      return false;
    }
    if (info.getPersonalInfo().getMarried().isEmpty()) {
      ToastUtils.showShort("请选择婚姻状况");
      return false;
    }
    if (info.getPersonalInfo().getEducation().isEmpty()) {
      ToastUtils.showShort("请选择学历");
      return false;
    }
    if (info.getPersonalInfo().getGraduateTime().isEmpty()) {
      ToastUtils.showShort("请选择毕业时间");
      return false;
    }
    if (info.getPersonalInfo().getWorkTime().isEmpty()) {
      ToastUtils.showShort("请选择工作年资");
      return false;
    }
//        if (info.getPersonalInfo().getCollege().isEmpty()) {
//            ToastUtils.showShort("请填写毕业院校");
//            return false;
//        }
//        if (info.getPersonalInfo().getSpecialty().isEmpty()) {
//            ToastUtils.showShort("请填写所学专业");
//            return false;
//        }
//        if (info.getPersonalInfo().getGrowthExp().isEmpty()) {
//            ToastUtils.showShort("请填写成长经历");
//            return false;
//        }

    // 检查爱好和性格数据
    if (info.getPersonalInterest().getHobby().isEmpty()) {
      ToastUtils.showShort("请选择爱好");
      return false;
    }
    if (info.getPersonalInterest().getSport().isEmpty()) {
      ToastUtils.showShort("请选择运动");
      return false;
    }
    if (info.getPersonalInterest().getTravel().isEmpty()) {
      ToastUtils.showShort("请选择旅游");
      return false;
    }
    if (info.getPersonalInterest().getIntercourse().isEmpty()) {
      ToastUtils.showShort("请选择交往");
      return false;
    }
    if (info.getPersonalInterest().getLiving().isEmpty()) {
      ToastUtils.showShort("请选择居住");
      return false;
    }
    if (info.getPersonalInterest().getCharacter().isEmpty()) {
      ToastUtils.showShort("请选择性格");
      return false;
    }

    // 检查注册资料数据
    if (info.getNeed().getPhoneNo().isEmpty() || !FormatUtils
        .isMobileNO(info.getNeed().getPhoneNo())) {
      ToastUtils.showShort("请输入正确的手机号");
      return false;
    }
    if ((info.getNeed().getPassword().length() < 6) || (info.getNeed().getPassword().length()
        > 16)) {
      ToastUtils.showShort("密码长度范围6~16位");
      return false;
    }
    if (info.getNeed().getSmscode().isEmpty()) {
      ToastUtils.showShort("请输入验证码");
      return false;
    }

    return true;
  }

  /**
   * Des:将ScrollView的子控件移至顶部
   *
   * @param inner 子控件View
   */
  private void scrollToTop(final View inner) {
    mMainHandler.post(new Runnable() {
      public void run() {
        if (inner == null) {
          return;
        }
        // 获取子控件的位置
        int[] location = new int[2];
        inner.getLocationOnScreen(location);
        int y = location[1];
        // 计算子控件当前位置和ScrollView位置的Y轴差值
        int offset = y - mScrollView.getTop();
        // 与顶部保持一定的距离
        offset -= DisplayUtils.dip2px(10);
        // 如果差值大于0, 则
        if (offset > 0) {
          mScrollView.smoothScrollBy(0, offset);
        }
      }
    });
  }

    /*--------------------------------------------------------------------------------
     *                          爱好和性格接口实现
     ---------------------------------------------------------------------------------*/

  /**
   * Des:获取爱好子项目选中数据
   *
   * @param list 解析二级爱好的列表
   * @param separator 分隔符
   */
  private String getInterestCheckedData(List<Interest> list, String separator) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < list.size(); i++) {
      Interest interest = list.get(i);
      if (interest.isChecked) {
        sb.append(interest.label).append(separator);
      }
    }
    if (sb.length() > 0) {
      sb.deleteCharAt(sb.length() - 1);
    }

    return sb.toString();
  }

  /**
   * Des:加载爱好子项目选中数据
   *
   * @param editText 要加载的EditText对象
   * @param data 数据
   */
  private void loadInterestCheckedData(final EditText editText, String data) {
    editText.setText(data);
    editText.post(new Runnable() {
      @Override
      public void run() {
        if (editText.getLineCount() > 1) {
          editText.setGravity(Gravity.LEFT);
        } else {
          editText.setGravity(Gravity.RIGHT);
        }
      }
    });
  }

  /**
   * Des:初始化爱好子项目显示数据
   */
  private void showInterestData() {
    loadInterestCheckedData(mHobbyEdit,
        getInterestCheckedData(((AppApplication) getApplicationContext()).getHobbyList(), "、"));
    loadInterestCheckedData(mSportEdit,
        getInterestCheckedData(((AppApplication) getApplicationContext()).getSportList(), "、"));
    loadInterestCheckedData(mTravelEdit,
        getInterestCheckedData(((AppApplication) getApplicationContext()).getTravelList(), "、"));
    loadInterestCheckedData(mIntercourseEdit,
        getInterestCheckedData(((AppApplication) getApplicationContext()).getIntercourseList(), "、"));
    loadInterestCheckedData(mLivingEdit,
        getInterestCheckedData(((AppApplication) getApplicationContext()).getLivingList(), "、"));
    loadInterestCheckedData(mCharacterEdit,
        getInterestCheckedData(((AppApplication) getApplicationContext()).getCharacterList(), "、"));
  }

    /*--------------------------------------------------------------------------------
     *                          仿iOS的PickerView组件集合
     ---------------------------------------------------------------------------------*/

  /**
   * Des:构建选择器(公司)
   */
  private FlatOptionsPickerView buildCompanyPickerView() {
    FlatOptionsPickerView pvOptions = new FlatOptionsPickerView
        .Builder(this, new FlatOptionsPickerView.OnOptionsSelectListener() {
      @Override
      public void onOptionsSelect(int options1, int option2, int options3, View v) {
        mCompanyEdit.setText(mCompanyList.get(options1));
        mCompanyEdit.requestFocus();
        // 当选择的公司发生切换时,则同时切换单位列表
        reloadParkOptionData(options1);
      }
    }, 0)
        .setSelectOptions(0)  //设置默认选中项
        .build();

    pvOptions.setPicker(mCompanyList);//添加数据源
    return pvOptions;
  }

  /**
   * Des:构建选择器(单位)
   */
  private FlatOptionsPickerView buildParkPickerView(final ArrayList<String> list) {
    FlatOptionsPickerView pvOptions = new FlatOptionsPickerView
        .Builder(this, new FlatOptionsPickerView.OnOptionsSelectListener() {
      @Override
      public void onOptionsSelect(int options1, int option2, int options3, View v) {
        mParkEdit.setText(list.get(options1));
        mParkEdit.requestFocus();
      }
    }, 0)
        .setSelectOptions(0)  //设置默认选中项
        .build();

    pvOptions.setPicker(list);//添加数据源
    return pvOptions;
  }

  /**
   * Des:构建选择器(性别)
   */
  private FlatOptionsPickerView buildSexPickerView() {
    FlatOptionsPickerView pvOptions = new FlatOptionsPickerView
        .Builder(this, new FlatOptionsPickerView.OnOptionsSelectListener() {
      @Override
      public void onOptionsSelect(int options1, int option2, int options3, View v) {
        mSexEdit.setText(mSexList.get(options1));
      }
    }, 0)
        .setSelectOptions(0)  //设置默认选中项
        .build();

    pvOptions.setPicker(mSexList);//添加数据源
    return pvOptions;
  }

  /**
   * Des:构建选择器(出生年月)
   */
  private FlatTimePickerView buildBirthdayPickerView() {
    FlatTimePickerView pvTime = new FlatTimePickerView
        .Builder(this, new FlatTimePickerView.OnTimeSelectListener() {
      @Override
      public void onTimeSelect(Date date, View v) {//选中事件回调
        mBirthdayEdit.setText(DateFormat.format("yyyy年MM月", date));
      }
    }, 0)
        .build();

    return pvTime;
  }

  /**
   * Des:构建选择器(民族)
   */
  private FlatOptionsPickerView buildRacePickerView() {
    FlatOptionsPickerView pvOptions = new FlatOptionsPickerView
        .Builder(this, new FlatOptionsPickerView.OnOptionsSelectListener() {
      @Override
      public void onOptionsSelect(int options1, int option2, int options3, View v) {
        mRaceEdit.setText(mRaceList.get(options1));
      }
    }, 0)
        .setSelectOptions(0)  //设置默认选中项
        .build();

    pvOptions.setPicker(mRaceList);//添加数据源
    return pvOptions;
  }

  /**
   * Des:构建选择器(婚姻)
   */
  private FlatOptionsPickerView buildMaritalPickerView() {
    FlatOptionsPickerView pvOptions = new FlatOptionsPickerView
        .Builder(this, new FlatOptionsPickerView.OnOptionsSelectListener() {
      @Override
      public void onOptionsSelect(int options1, int option2, int options3, View v) {
        mMaritalEdit.setText(mMaritalList.get(options1));
      }
    }, 0)
        .setSelectOptions(0)  //设置默认选中项
        .build();

    pvOptions.setPicker(mMaritalList);//添加数据源
    return pvOptions;
  }

  /**
   * Des:构建选择器(学历)
   */
  private FlatOptionsPickerView buildEducationPickerView() {
    FlatOptionsPickerView pvOptions = new FlatOptionsPickerView
        .Builder(this, new FlatOptionsPickerView.OnOptionsSelectListener() {
      @Override
      public void onOptionsSelect(int options1, int option2, int options3, View v) {
        mEducationEdit.setText(mEducationList.get(options1));
      }
    }, 0)
        .setSelectOptions(0)  //设置默认选中项
        .build();

    pvOptions.setPicker(mEducationList);//添加数据源
    return pvOptions;
  }

  /**
   * Des:构建选择器(毕业时间)
   */
  private FlatTimePickerView buildGraduateTimePickerView() {
    FlatTimePickerView pvTime = new FlatTimePickerView
        .Builder(this, new FlatTimePickerView.OnTimeSelectListener() {
      @Override
      public void onTimeSelect(Date date, View v) {//选中事件回调
        mGraduateTimeEdit.setText(DateFormat.format("yyyy年MM月", date));
      }
    }, 0)
        .build();

    return pvTime;
  }

  /**
   * Des:构建选择器(工作年资)
   */
  private FlatOptionsPickerView buildWorktimePickerView() {
    FlatOptionsPickerView pvOptions = new FlatOptionsPickerView
        .Builder(this, new FlatOptionsPickerView.OnOptionsSelectListener() {
      @Override
      public void onOptionsSelect(int options1, int option2, int options3, View v) {
        mWorktimeEdit.setText(mWorktimeList.get(options1));
      }
    }, 0)
        .setSelectOptions(0)  //设置默认选中项
        .build();

    pvOptions.setPicker(mWorktimeList);//添加数据源
    return pvOptions;
  }

  /*--------------------------------------------------------------------------------
   *                          点击事件接口实现
   ---------------------------------------------------------------------------------*/
//  // 选择单位代码
//  @OnClick(R.id.et_company)
//  public void clickSelectCompany() {
////    SoftInputUtils.hideSoftKeyboard(this);
//    scrollToTop(mCompanyEdit);
//
////    if (null == mCompanyFOPV) {
////      mCompanyFOPV = buildCompanyPickerView();
////    }
////    mCompanyFOPV.show();
//  }

  // 选择分支机构
  @OnClick(R.id.et_park)
  public void clickSelectPark() {
    // 判断是否已选择公司
    if (mCompanyCode.isEmpty()) {
      ToastUtils.showShort("请先输入有效的单位代码");
      return;
    }

    SoftInputUtils.hideSoftKeyboard(this);
    scrollToTop(mParkEdit);

    if (null == mParkFOPV) {
      mParkFOPV = buildParkPickerView(mParkList);
    }
    mParkFOPV.show();
  }

  // 选择性别
  @OnClick(R.id.et_sex)
  public void clickSelectSex() {
    SoftInputUtils.hideSoftKeyboard(this);
    scrollToTop(mSexEdit);

    if (null == mSexFOPV) {
      mSexFOPV = buildSexPickerView();
    }
    mSexFOPV.show();
  }

  // 选择出生年月
  @OnClick(R.id.et_birthday)
  public void clickSelectBirthday() {
    SoftInputUtils.hideSoftKeyboard(this);
    scrollToTop(mBirthdayEdit);

    if (null == mBirthdayFTPV) {
      mBirthdayFTPV = buildBirthdayPickerView();
    }
    mBirthdayFTPV.show();
  }

  // 选择民族
  @OnClick(R.id.et_race)
  public void clickSelectRace() {
    SoftInputUtils.hideSoftKeyboard(this);
    scrollToTop(mRaceEdit);

    if (null == mRaceFOPV) {
      mRaceFOPV = buildRacePickerView();
    }
    mRaceFOPV.show();
  }

  // 选择婚姻
  @OnClick(R.id.et_marital)
  public void clickSelectMarital() {
    SoftInputUtils.hideSoftKeyboard(this);
    scrollToTop(mMaritalEdit);

    if (null == mMaritalFOPV) {
      mMaritalFOPV = buildMaritalPickerView();
    }
    mMaritalFOPV.show();
  }

  // 选择学历
  @OnClick(R.id.et_education)
  public void clickSelectEducation() {
    SoftInputUtils.hideSoftKeyboard(this);
    scrollToTop(mEducationEdit);

    if (null == mEducationFOPV) {
      mEducationFOPV = buildEducationPickerView();
    }
    mEducationFOPV.show();
  }

  // 选择毕业时间
  @OnClick(R.id.et_graduate_time)
  public void clickSelectGraduateTime() {
    SoftInputUtils.hideSoftKeyboard(this);
    scrollToTop(mGraduateTimeEdit);

    if (null == mGraduateTimeFTPV) {
      mGraduateTimeFTPV = buildGraduateTimePickerView();
    }
    mGraduateTimeFTPV.show();
  }

  // 选择工作年资
  @OnClick(R.id.et_worktime)
  public void clickSelectWorktime() {
    SoftInputUtils.hideSoftKeyboard(this);
    scrollToTop(mWorktimeEdit);

    if (null == mWorktimeFOPV) {
      mWorktimeFOPV = buildWorktimePickerView();
    }
    mWorktimeFOPV.show();
  }

  // 选择爱好
  @OnClick({R.id.et_hobby, R.id.iv_hobby})
  public void clickSelectHobby() {
    SoftInputUtils.hideSoftKeyboard(this);
    scrollToTop(mHobbyEdit);

    Bundle bundle = new Bundle();
    bundle.putString(AppConstant.BUNDLE_INTEREST_TAG_NAME, AppConstant.INTEREST_HOBBY);
    ActTransAnimUtils
        .startActionSlideRightToLeft(RegisterActivity.this, InterestActivity.class, bundle);
  }

  // 选择运动
  @OnClick({R.id.et_sport, R.id.iv_sport})
  public void clickSelectDiet() {
    SoftInputUtils.hideSoftKeyboard(this);
    scrollToTop(mSportEdit);

    Bundle bundle = new Bundle();
    bundle.putString(AppConstant.BUNDLE_INTEREST_TAG_NAME, AppConstant.INTEREST_SPORT);
    ActTransAnimUtils
        .startActionSlideRightToLeft(RegisterActivity.this, InterestActivity.class, bundle);
  }

  // 选择旅游
  @OnClick({R.id.et_travel, R.id.iv_travel})
  public void clickSelectTravel() {
    SoftInputUtils.hideSoftKeyboard(this);
    scrollToTop(mTravelEdit);

    Bundle bundle = new Bundle();
    bundle.putString(AppConstant.BUNDLE_INTEREST_TAG_NAME, AppConstant.INTEREST_TRAVEL);
    ActTransAnimUtils
        .startActionSlideRightToLeft(RegisterActivity.this, InterestActivity.class, bundle);
  }

  // 选择交往
  @OnClick({R.id.et_intercourse, R.id.iv_intercourse})
  public void clickSelectIntercourse() {
    SoftInputUtils.hideSoftKeyboard(this);
    scrollToTop(mIntercourseEdit);

    Bundle bundle = new Bundle();
    bundle.putString(AppConstant.BUNDLE_INTEREST_TAG_NAME, AppConstant.INTEREST_INTERCOURSE);
    ActTransAnimUtils
        .startActionSlideRightToLeft(RegisterActivity.this, InterestActivity.class, bundle);
  }

  // 选择居住
  @OnClick({R.id.et_living, R.id.iv_living})
  public void clickSelectLiving() {
    SoftInputUtils.hideSoftKeyboard(this);
    scrollToTop(mLivingEdit);

    Bundle bundle = new Bundle();
    bundle.putString(AppConstant.BUNDLE_INTEREST_TAG_NAME, AppConstant.INTEREST_LIVING);
    ActTransAnimUtils
        .startActionSlideRightToLeft(RegisterActivity.this, InterestActivity.class, bundle);
  }

  // 选择性格
  @OnClick({R.id.et_character, R.id.iv_character})
  public void clickSelectCharacter() {
    SoftInputUtils.hideSoftKeyboard(this);
    scrollToTop(mCharacterEdit);

    Bundle bundle = new Bundle();
    bundle.putString(AppConstant.BUNDLE_INTEREST_TAG_NAME, AppConstant.INTEREST_CHARACTER);
    ActTransAnimUtils
        .startActionSlideRightToLeft(RegisterActivity.this, InterestActivity.class, bundle);
  }

  // 获取验证码
  @OnClick(R.id.tv_smscode)
  public void clickGetSmscode() {
    // 获取手机号
    mPhoneStr = mPhoneEdit.getText().toString().trim();
    // 检查手机号有效性
    if (mPhoneStr.isEmpty() || !FormatUtils.isMobileNO(mPhoneStr)) {
      ToastUtils.showShort("请输入正确的手机号");
      return;
    }
    // 发送获取验证码请求
    mRxManager.add(ApiRequest.requestGetSmscode(mPhoneStr, 1)
        .subscribe(new RxSubscriber<String>(mContext) {
          @Override
          protected void _onNext(String msg) {
            // 响应处理
            if (GsonUtils.getIntValue(msg, "error") == 0) {
              ToastUtils.showShort("获取验证码成功");
              // 启动验证码按钮倒计时动作
              SmscodeCountDownTimerUtils mCountDownTimerUtils = new SmscodeCountDownTimerUtils(
                  mSmscodeText, 90000, 1000);
              mCountDownTimerUtils.start();
            } else {
              String reason = GsonUtils.getValue(msg, "reason");
              ApiConstants.showError(reason);
            }
          }

          @Override
          protected void _onError(String message) {
            // TODO:处理错误响应
            ToastUtils.showShort("获取验证码失败:" + message);
          }
        }));
  }

  // 是否已阅读并同意服务协议
  @OnClick(R.id.ll_note_checkbox)
  public void clickAgree() {
    isAgree = !isAgree;
    if (isAgree) {
      mAgreeImage.setImageResource(R.drawable.ic_checkbox_checked);
    } else {
      mAgreeImage.setImageResource(R.drawable.ic_checkbox_unchecked);
    }
  }

  // 跳转到《用户注册服务协议》页面
  @OnClick(R.id.tv_note_2)
  public void clickReadAgreement() {
    ActTransAnimUtils.startActionPushDown(RegisterActivity.this, AgreementActivity.class);
  }

  // 注册并登录
  @OnClick(R.id.btn_next)
  public void clickNext() {
    // 重载全部数据
    RegisterInfo info = reloadAllEditData();
    // 检查数据有效性
    if (!checkAllEditData(info)) {
      return;
    }
    // 检查是否已阅读并同意协议
    if (!isAgree) {
      ToastUtils.showShort("请先阅读并同意《用户注册服务协议》");
      return;
    }
    // 发送网络请求
    mRxManager.add(ApiRequest.requestRegister(info)
        .subscribe(new RxSubscriber<String>(mContext) {
          @Override
          protected void _onNext(String msg) {
            int errorCode = GsonUtils.getIntValue(msg, "error");
            String reason = GsonUtils.getValue(msg, "reason");
            // 响应处理
            if (errorCode == 0) {
              ToastUtils.showShort("注册成功");
              // 解析响应
              String result = GsonUtils.getValue(msg, "result");
              UserInfo userInfo = (UserInfo) GsonUtils.fromJson(result, UserInfo.class);
              // 保存用户信息
              ((AppApplication) getApplicationContext()).setLoginUser(userInfo);
              // 标记为已登录状态
              ((AppApplication) getApplicationContext()).setIsUserLogin(true);
              // 重置爱好缓存数据
              ((AppApplication) getApplicationContext()).resetInterestList();
              // 返回登录界面
              ActTransAnimUtils.finishActionSlideLeftToRight(RegisterActivity.this);
            } else if (errorCode == 3) {
              ToastUtils.showShort(reason);
            } else {
              ApiConstants.showError(reason);
            }
          }

          @Override
          protected void _onError(String message) {
            // TODO:处理失败响应
            ToastUtils.showShort("注册并登录失败:" + message);
          }
        }));
  }

    /*--------------------------------------------------------------------------------
     *                          系统键处理
     ---------------------------------------------------------------------------------*/

  /**
   * 监听主页键,返回键
   */
  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
      // 重置爱好缓存数据
      ((AppApplication) getApplicationContext()).resetInterestList();
      // 返回登录页面
      ActTransAnimUtils.finishActionSlideLeftToRight(RegisterActivity.this);
      return true;
    }
    return super.onKeyDown(keyCode, event);
  }

}
